using Microsoft.EntityFrameworkCore;
using NLog.Web;
using System.Reflection;
using WMS.RealTime.Infrastructure;
using WMS.RealTime.API.Hubs;
using WMS.RealTime.API.Services;
using WMS.RealTime.Servers.Services;
using WMS.RealTime.IServers.Interfaces;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "WMS.RealTime.API.xml", true));

// 日志配置
builder.Host.UseNLog();

// 跨域配置
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyHeader()
              .AllowAnyMethod()
              .AllowAnyOrigin();
    });
});

// SignalR配置
builder.Services.AddSignalR(options =>
{
    options.EnableDetailedErrors = builder.Configuration.GetValue<bool>("SignalR:EnableDetailedErrors");
    options.ClientTimeoutInterval = TimeSpan.FromSeconds(builder.Configuration.GetValue<int>("SignalR:ClientTimeoutInterval"));
    options.KeepAliveInterval = TimeSpan.FromSeconds(builder.Configuration.GetValue<int>("SignalR:KeepAliveInterval"));
});

// 数据库配置
builder.Services.AddDbContext<RealTimeDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 中介者模式
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));

// AutoMapper配置
builder.Services.AddAutoMapper(Assembly.GetExecutingAssembly());

// 注册HTTP客户端
builder.Services.AddHttpClient();

// 注册服务
builder.Services.AddScoped<IWMSDataService, WMSDataService>();
builder.Services.AddScoped<IDashboardDataService, DashboardDataService>();
builder.Services.AddSingleton<IDashboardHub, DashboardHubProxy>();
builder.Services.AddSingleton<IRealTimePushService, RealTimePushService>();

// 后台服务
builder.Services.AddHostedService<DashboardBackgroundService>();

var app = builder.Build();

// 跨域中间件
app.UseCors("AllowAll");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

// 映射SignalR Hub
app.MapHub<DashboardHub>("/dashboardHub");

app.Run();
